package service

import (
    "fmt"
    "ginBlog/models"
    "strconv"
)

type Tag struct {
    ID      int     `json:"id" db:"id"`
    TagName string `json:"tag_name" db:"tag_name" binding:"required,max=16"`
}

type Tags struct {
    Items   []Tag  `json:"items"`
    Total   int     `json:"total"`
}

var db = models.DB

func (t *Tag) Create() (Tag, error) {
    r, e := db.Exec("insert into blog_tag (tag_name) values (?)", t.TagName)
    if e != nil {
        return Tag{}, e
    }
    id,_ := r.LastInsertId()
    return Tag{int(id), t.TagName}, nil
}

func (t *Tag) Delete() error {
    _,e := db.Exec("delete from blog_tag where id=?", t.ID)
    return e
}

func (t *Tag) Edit() error {
    _, e := db.Exec("update blog_tag set tag_name=? where id=?", t.TagName, t.ID)

    return e
}

func (t *Tag) GetOne() (Tag, error)  {
    var tag Tag
    e := db.Get(&tag, "select * from blog_tag where id=?", t.ID)
    return tag, e
}

func (t Tag) GetAll(limit, page string) (data Tags, err error)  {
    baseSql := "select %s from blog_tag t"
    var p,l int
    if limit != "" && page != "" {
        p,_ = strconv.Atoi(page)
        l,_ = strconv.Atoi(limit)
    }

    tags := make([]Tag, 0)
    offset := (p - 1) * l
    selectSql := fmt.Sprintf(baseSql, "t.id, t.tag_name") + fmt.Sprintf(" ORDER BY t.id DESC limit %d offset %d", l, offset)
    if err = db.Select(&tags, selectSql); err != nil {
        return
    }

    var total int
    if err = db.Get(&total, fmt.Sprintf(baseSql, "count(1)")); err != nil {
        return
    }

    data.Items = tags
    data.Total = total
    return
}